'''
Created on Feb 13, 2014

@author: yfrank
'''

import Transport.Peer as Peer

import CodingUtils.Geometry as Geometry

from Commands.Message import OutputMessage as OutputMessage

import Simulation.SimulationPeerStateMacine as SimulationPeerStateMacine

import Simulation.PathUtils as PathUtils

class SimulationPeer(Peer.Peer):
    '''
    classdocs
    '''
    def __init__(self,ch,dirname):
        sm = SimulationPeerStateMacine.SimulationPeerStateMacine(self)
        super(SimulationPeer,self).__init__(ch,sm)
        self.path_gen = PathUtils.PathFunctions(self)
        self.dirname = dirname
        self.workspace= []
        self.targets= []
        self.sources= []
        self.robots= []

    def parse_input(self,buff):
        l_buff = buff.split('|')
        assert len(l_buff) == 4
        if not self.parse_workspase(l_buff[0]): return False
        if not self.parse_robots(l_buff[1]): return False
        if not self.parse_sources(l_buff[2]): return False
        if not self.parse_targets(l_buff[3]): return False
        return True

    def send_output(self,num_path):
        paths = []
        dirname = str(self.get_channel().get_port())+"\\"
        for i in range(1,num_path+1):
            f = open(dirname+"path_"+str(i)+".txt",'r')
            paths.append(f.read())
            f.close()
        msg = OutputMessage(paths)
        self.send_message(str(msg))

    def send_failure(self,msg):
        buff = "ERROR: "+str(msg)
        self.send_message(buff)

    def parse_workspase(self,buff):
        filename = "\\workspace.txt"
        self.write_to(buff,filename)
        return True

    def parse_robots(self,buff):
        filename = "\\robot.txt"
        self.write_to(buff,filename)
        return True

    def parse_sources(self,buff):
        filename = "\\source.txt"
        self.write_to(buff,filename)
        return True

    def parse_targets(self,buff):
        filename = "\\target.txt"
        self.write_to(buff,filename)
        return True

    def write_to(self,buff,filename):
        dirname = self.dirname
        path = dirname+filename
        f = open(path,'w+')
        f.write(buff)
        f.close()

    def calculate_path(self):
        self.path_gen.do_calculate_path(self.dirname)
